import uuid
from django.utils import timezone
from django.db import transaction
from typing import List, Dict, Any

from delivery.service.replenishment_service import MovingAverage
from events.models import StoreProductReplenishment, StoreReplenishment
from utils.IOService import get_order_detail, get_inventory


class DeliveryGenerator:
    def __init__(self):
        self.order_detail = get_order_detail()
        self.ma = MovingAverage(self.order_detail)
        self.instock_inventory = get_inventory()
        self.delivery_result = None

    def generate_delivery(self) -> None:
        """生成补货建议"""
        try:
            # 获取销量预测
            sales_quantity = self.ma.fitting()
            
            # 合并库存数据
            delivery_feed = self.instock_inventory.merge(
                sales_quantity, 
                on='product_code', 
                how='left'
            )
            
            # 生成补货建议
            self.delivery_result = self.ma.predicting(delivery_feed)
            
            # 添加必要字段
            self._add_required_fields()
            # 删除不必要字段
            self._drop_unnecessary_fields()
            
        except Exception as e:
            raise RuntimeError(f"生成补货建议失败: {str(e)}")

    def _add_required_fields(self) -> None:
        """添加必要的字段"""
        if self.delivery_result is None:
            raise ValueError("delivery_result 不能为空")
            
        current_time = timezone.localtime()
        self.delivery_result['created_at'] = current_time
        self.delivery_result['order_date'] = current_time.date()
        self.delivery_result['is_cancelled'] = False
        self.delivery_result['order_id'] = str(uuid.uuid4())

    def _drop_unnecessary_fields(self):
        """<UNK>"""
        self.delivery_result.drop(['id','delivery_quantity', 'updated_at','quantity', 'demand_variance', 'is_replenishment'],axis=1, inplace=True)

    def batch_insert(self) -> int:
        """批量插入数据库
        
        Returns:
            int: 插入的记录数
        
        Raises:
            ValueError: 当delivery_result为空时
            RuntimeError: 当插入失败时
        """
        if self.delivery_result is None:
            raise ValueError("没有可插入的补货建议数据")
            
        try:
            records = self.delivery_result.to_dict('records')
            replenishment = [
                StoreProductReplenishment(**record) 
                for record in records
            ]
            
            with transaction.atomic():
                # 创建补货建议记录
                created = StoreProductReplenishment.objects.bulk_create(
                    replenishment,
                    ignore_conflicts=True
                )
                
                # 创建补货记录
                if len(created) > 0:
                    # 使用第一条记录的order_id和order_date
                    first_record = replenishment[0]
                    StoreReplenishment.objects.create(
                        order_id=first_record.order_id,
                        order_date=first_record.order_date
                    )
                
            return len(created)
            
        except Exception as e:
            raise RuntimeError(f"批量插入补货建议失败: {str(e)}")


def generate_and_save_delivery() -> Dict[str, Any]:
    """生成并保存补货建议的主函数
    
    Returns:
        Dict[str, Any]: 包含处理结果的字典
    """
    try:
        generator = DeliveryGenerator()
        generator.generate_delivery()
        inserted_count = generator.batch_insert()
        
        return {
            "success": True,
            "message": f"成功生成并保存{inserted_count}条补货建议",
            "count": inserted_count
        }
        
    except Exception as e:
        return {
            "success": False,
            "message": str(e),
            "count": 0
        }


